package gui;

import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

import main.EpistocracyApplet;

public class WaitingPanel extends JPanel
{
	private JLabel lblTimer = new JLabelWhite();
	private JPanel timerPanel = new TransparentPanel();
	private TimerTask task;
	private long count;
	private EpistocracyApplet applet;

	public WaitingPanel(final EpistocracyApplet applet)
	{
		this.applet = applet;
		setBounds(0, 370, 450, 50);
		setLayout(null);
		setOpaque(false);
		JButton btnCancel = new JButton("Abbrechen");
		btnCancel.setBounds(344, 10, 100, 30);
		btnCancel.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				applet.cancelGameRequest();
				applet.sendCancelRequest();
			}
		});
		btnCancel.setBackground(Color.DARK_GRAY);
		btnCancel.setForeground(Color.WHITE);
		add(btnCancel);

		JLabel lblLabel = new JLabelWhite("Suche Mitspieler. Bitte warten...");
		lblLabel.setBounds(8, 18, 185, 14);
		add(lblLabel);

		lblTimer.setBounds(193, 18, 97, 14);
		lblTimer.setHorizontalAlignment(SwingConstants.RIGHT);
		lblTimer.setFont(getFont().deriveFont(18f));

		timerPanel.setBounds(0, 0, 450, 50);
		timerPanel.add(lblTimer);
		add(timerPanel);
	}

	public void timerAbbrechen()
	{
		task.cancel();
	}

	private String addDigits(long nr)
	{
		if (nr < 10)
			return "0" + nr;
		else
			return String.valueOf(nr);
	}

	private String getTimeString(long nr)
	{
		long sec = nr % 60;
		long min = (nr / 60) % 60;
		long hr = nr / 3600;
		if (hr == 0)
			return addDigits(min) + ":" + addDigits(sec);
		else
			return hr + ":" + addDigits(min) + ":" + addDigits(sec);
	}

	public void startTimer()
	{
		count = 0;
		Timer timer = new Timer();
		task = new TimerTask()
		{
			@Override
			public void run()
			{
				count++;
				lblTimer.setText(getTimeString(count));
			}
		};
		timer.schedule(task, 0, 1000);
	}
}